package com.kunbo.service;

import com.kunbo.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LikeService {

    @Autowired
    private RedisTemplate redisTemplate;

    //点赞
//    public void like(int userId, int entityType, int entityId){
//        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityId);
//        Boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);//判断在不在集合里
//        if(isMember){//返回true表示点过赞，就是取消赞
//            redisTemplate.opsForSet().remove(entityLikeKey, userId);
//        }else {
//            redisTemplate.opsForSet().add(entityLikeKey, userId);
//
//        }
//    }
       public Map<String, String> like(String conversationId, int userId){
           Map<String, String> map = new HashMap<>();
           String userLikeKey = RedisKeyUtil.getEntityLikeKey(conversationId, userId);
           String userLikeTime = RedisKeyUtil.getEntityLikeKey(userId);
           String[] s = conversationId.split("_");
           int toId = Integer.parseInt(s[0]);
           System.out.println(s[0]);
                   if(Integer.parseInt(s[0]) == userId){
                       toId = Integer.parseInt(s[1]);
                   }
           int finalToId = toId;
           redisTemplate.execute(new SessionCallback() {
               @Override
               public Object execute(RedisOperations redisOperations) throws DataAccessException {

                   int LastTime = (int)redisTemplate.opsForValue().get(userLikeTime);
                   redisOperations.multi();
                   if(LastTime <= 0){
                       map.put("likeMsg", "推荐次数上限，推荐失败");
                   }else {
                       redisTemplate.opsForValue().set(userLikeKey, finalToId);
                       redisTemplate.opsForValue().decrement(userLikeTime);
                       map.put("likeMsg", "推荐成功");
                   }
                    return redisOperations.exec();
               }
           });
           return map;
       }

    //查询某实体点赞的数量
    public int findEntityLikeCount(int entityType, int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityId);
        return 3 - (int)redisTemplate.opsForValue().get(entityLikeKey);
    }

    //查询某人对某实体的点赞状态
    public int findEntityLikeStatus(String conversationId, int userId){
        String userLikeKey = RedisKeyUtil.getEntityLikeKey(conversationId, userId);
        return redisTemplate.hasKey(userLikeKey) ? 1 : 0;
    }
}
